#include "./Router.h"

bool Router::route(const HttpRequest &req, HttpResponse *res)
{
    Key key{req.getMethod(), req.getPath()};

    // 静态路由
    auto handlerFuncsIt = this->handlerFuncs_.find(key);
    if (handlerFuncsIt != this->handlerFuncs_.end())
    {
        handlerFuncsIt->second(req, res);
        return true;
    }

    auto handlerPtrsIt = this->handlerPtrs_.find(key);
    if (handlerPtrsIt != this->handlerPtrs_.end())
    {
        handlerPtrsIt->second->handle(req, res);
        return true;
    }

    // 动态路由
    for (const auto &[method, pathRegex, handlerFunc] : regexhandlerFuncs_)
    {
        std::string pathStr(req.getPath());
        std::smatch match{};
        if (method == req.getMethod() && std::regex_match(pathStr, match, pathRegex))
        {
            // 传入req是const&不可改，用新req回调
            HttpRequest newReq(req);
            this->extractPathParameters(match, newReq);

            handlerFunc(newReq, res);
            return true;
        }
    }

    for (const auto &[method, pathRegex, handlerPtr] : this->regexhandlerPtrs_)
    {
        std::string pathStr(req.getPath());
        std::smatch match{};
        if (method == req.getMethod() && std::regex_match(pathStr, match, pathRegex))
        {
            HttpRequest newReq(req);
            this->extractPathParameters(match, newReq);

            handlerPtr->handle(newReq, res);
            return true;
        }
    }

    return false;
}